import settings from "@/settings";
import { getEnterpriseId } from "@/utils/getEnterpriseId";
import UrlFactory from "./urlFactory.js";
import {parseExtStr} from './parseExtStr.js'

export const getAuthenSK = async (goUrl, key) => {
  try {
    const enterpriseId = getEnterpriseId();
    const urlProcessor = UrlFactory.getInstance();

    if (!enterpriseId) {
      alert("请传递站点参数");
      return;
    }
    const originUrl = !!goUrl ? goUrl : urlProcessor.encodeUrlStr();

    // 获取油企信息
    const enterpriseInfo = await $nuxt.$axios.$get("/selectEnterpriseInfo", {
      params: {
        enterpriseId: enterpriseId
      }
    });

    $nuxt.$store.commit("authen/setEnterpriseInfo", enterpriseInfo.data);// 保存油企信息


    // 无openid，先跳转获取openid
    if (!$nuxt.$store.getters["authen/openId"]) {
      console.log("我要微信认证了",originUrl); 
      
      // 获取appid
      $nuxt.$store.dispatch("authen/getAppId", enterpriseId).then((res) => {
        sessionStorage.setItem("enterpriseId", enterpriseId);
        $nuxt.$store.commit("authen/setEnterpriseId", enterpriseId);

        if (enterpriseInfo.data["gzhAppSecret"] != undefined) {
          console.log('有密钥--老版本授权')
          // 老版本授权
          window.location.href =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
            $nuxt.$store.getters["authen/appId"] +
            "&redirect_uri=" +
            settings.baseUrl +
            "remitAuthSk&response_type=code&scope=snsapi_base&state=" +
            originUrl +
            "#wechat_redirect";
            
        } else {
          // 新版本授权
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${$nuxt.$store.getters["authen/appId"]}&redirect_uri=${settings.baseUrl}remitAuthSk&response_type=code&scope=snsapi_base&state=${originUrl}&component_appid=${settings.componentAppid}#wechat_redirect`;
        }
      }).catch((error) => {
        alert(error+'失败')
      })
      return; 
    }
  
      let urlInfo = parseExtStr(originUrl)
      console.log('url--参数解析：', urlInfo);
      console.log('url--参数解析---stationName：', urlInfo.searchObj.stationName);
      console.log('url--参数解析---stationId：', urlInfo.searchObj.stationId);
       
      // 直接跳转到收款页面   
      let url = `/${urlInfo.enterpriseId}/pay/?stationId=${urlInfo.searchObj.stationId}&stationName=${urlInfo.searchObj.stationName}`
      window.location.href = url  
    
  } catch (e) {
    const msg = !!e.message ? e.message : e;
    alert(msg);
  }
};
